package work.ib.trs;

import java.io.BufferedWriter;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.regex.Pattern;

import org.apache.commons.lang.StringUtils;

import work.managercenter.ComplexChars;

public class UnitPageMapGenerator {

	public static final HashMap<String, String> hComplexes = new HashMap<String, String>();
	private static final Pattern cleanUrlPattern = Pattern.compile("(--|[^a-z0-9])+");

	public static void main(String[] args) {

		try {
			run();
		} catch (Exception e) {
			e.printStackTrace(System.out);
		}
	}

	private static void run() throws SQLException {
		Connection conn = null;
		Statement st = null;
		ResultSet rs = null;

		try {
			conn = getDBConnection();
			conn.setAutoCommit(false);
			st = conn.createStatement();
			rs = st.executeQuery("select c.complex_id, c.complex_name, c.city, c.state, u.unit_id from unit u join aptcomplexes c on c.complex_id = u.complex_id group by c.complex_id, u.unit_id");

			while (rs.next()) {
				String complex_id = rs.getString("complex_id");
				String name = rs.getString("complex_name");
				String city = rs.getString("city");
				String state = rs.getString("state");
				String unit_id = rs.getString("unit_id");

				addComplexToHash(complex_id, name, city, state, unit_id);
			}

		} finally {
			if (rs != null) {
				try {
					rs.close();
					rs = null;
				} catch (Exception e) {
					e.printStackTrace(System.out);
				}
			}
			if (st != null) {
				try {
					st.close();
					st = null;
				} catch (Exception e) {
					e.printStackTrace(System.out);
				}
			}
			if (conn != null) {
				try {
					conn.close();
					conn = null;
				} catch (Exception e) {
					e.printStackTrace(System.out);
				}
			}
		}


		printMap();
	}

	private static void printMap() {

		Writer writer = null;

		try {
			writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream("/home/gmarcone/trsunitmap.txt"), "utf-8"));

			for (Entry<String, String> entry: hComplexes.entrySet()) {
				writer.write(entry.getKey() + " " + entry.getValue() + System.getProperty("line.separator"));
			}
		} catch (IOException e) {
			e.printStackTrace(System.out);
		} finally {
			if (writer != null) {
				try {
					writer.close();
				} catch (Exception e) {
					e.printStackTrace(System.out);
				}
			}
		}
	}

	private static final String dbURL = "jdbc:mysql://172.16.231.17:3306/aptsandrentals";
	private static final String dbUser = "aptsrentals";
	private static final String dbPassword = "Dov3bMHA";


	private static final Logger logger = Logger.getLogger(ComplexChars.class.getName());
	private static boolean driver_loaded = false;

	private synchronized static Connection getDBConnection() throws SQLException {

		if (!driver_loaded) {
			String driver = "com.mysql.jdbc.Driver";
			try {
				Class.forName(driver).newInstance();
				driver_loaded = true;
			} catch (Exception e) {
				logger.log(Level.SEVERE, null, e);
			}
		}

		return DriverManager.getConnection(dbURL, dbUser, dbPassword);
	}

	public static void addComplexToHash(String complex_id, String name, String city, String state, String unit_id){
		String strKey = unit_id;

		String bauxiteUrl = getBauxiteComplexUrl(state, city, name, complex_id);

		hComplexes.put(strKey, bauxiteUrl);
	}

	public static String getComplexKey(String strState, String strCity, String strComplex) {

		String strKeyWithState = _getComplexKey(strState, strCity, strComplex);
		String strComplexId = (String)hComplexes.get(strKeyWithState);

		if (!isNullString(strComplexId)) {
			return strKeyWithState;
		} else {
			return _getComplexKey(null, strCity, strComplex);
		}
	}

	public static boolean isNullString(String str) {
		if (str == null || str.equals("null")) {
			return true;
		}

		if (str.trim().length() > 0) {
			return false;
		} else {
			return true;
		}

	}

	private static String _getComplexKey(String state, String city, String complex) {

		if (null!=complex) {
			int idxFormerly = complex.indexOf("formerly");
			if (idxFormerly>0) {
				complex = complex.substring(0, idxFormerly);
			}
		}

		String strReturn = null;
		if (null==state) {
			strReturn = complex+"-IN-"+city;
		} else {
			strReturn = complex+"-IN-"+city+"-"+state;
		}

		return cleanUrlPattern.matcher(strReturn.toLowerCase().trim()).replaceAll("-");
	}

	private static Map<String, String> unsafechars = new HashMap<String, String>();

	static {
		unsafechars.put("(" , "");
		unsafechars.put(")" , "");
		unsafechars.put("Inc.", "");
		unsafechars.put("INC.", "");
		unsafechars.put("L.L.C.", "");
		unsafechars.put("L.L.C", "");
		unsafechars.put("!" , "");
		unsafechars.put("@" , "At");
		unsafechars.put("#" , "");
		unsafechars.put(":" , "");
		unsafechars.put("/" , " ");
		unsafechars.put("?" , "");
		unsafechars.put("&" , "And");
		unsafechars.put("'s" , "s");
		unsafechars.put("'S" , "S");
		unsafechars.put("'" , " ");
		unsafechars.put("." , " ");
		unsafechars.put("`","");
		unsafechars.put(",","");
		unsafechars.put("-"," ");
		unsafechars.put("-$","");
		unsafechars.put("-+","");
	}


	public static String getBauxiteComplexUrl(String state, String city, String complexName, String complexId) {

		for (Entry<String, String> entry : unsafechars.entrySet()) {
			String c = entry.getKey();
			String r = entry.getValue();

			state = StringUtils.normalizeSpace(state.replaceAll(Pattern.quote(c), r));
			city = StringUtils.normalizeSpace(city.replaceAll(Pattern.quote(c), r));
			complexName = StringUtils.normalizeSpace(complexName.replaceAll(Pattern.quote(c), r));
		}


		String complexUrl = ("/" + state + "/" + city + "/" + complexName).replaceAll("\\s+","-");

		complexUrl = complexUrl.toLowerCase() + "_" + complexId + "/";

		return complexUrl;
	}
}